<?php
/**
 * Base_App
 *
 * LICENSE
 *
 * This source file is subject to the new CC-GNU LGPL
 * It is available through the world-wide-web at this URL:
 * http://creativecommons.org/licenses/LGPL/2.1/
 *
 * @category   Base_App
 * @copyright  Copyright (c) 2009 Alexander fanatique* Thomas (me@alexander-thomas.net)
 * @license    http://creativecommons.org/licenses/LGPL/2.1/
 */

require_once 'Zend/Validate/Abstract.php';


class Base_App_Validation_Uniqueness extends Zend_Validate_Abstract implements Zend_Validate_Interface
{

    const IS_UNIQUE = 'isUnique';
    private $_db;
    private $_table;
    private $_column;
    
    function __construct($table, $column){
    	$this->_db = Zend_Registry::get('db');
    	$this->_table = $table;
    	$this->_column = $column;
    }


    protected $_messageTemplates = array(
        self::IS_UNIQUE => "Value is not unique"
    );

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value is not an empty value.
     *
     * @param  string $value
     * @return boolean
     */
    public function isValid($value)
    {
        $valueString = (string) $value;

        $this->_setValue($valueString);
		$row = $this->_db->fetchRow("SELECT count(1) AS count FROM " . $this->_table . " WHERE " . $this->_column . "= ?", $value );
		
		if ($row['count'] > 0) {
            $this->_error();
            return false;
        }

        return true;
    }

}
